<template>
  <div class="go-game-container">
    <!-- 调整为水平布局 -->
    <div class="game-layout">
      <!-- 棋盘区域 -->
      <div class="board-container">
        <div 
          class="go-board" 
          ref="boardRef"
          :style="{ width: boardSize + 'px', height: boardSize + 'px' }"
        >
          <!-- 棋盘网格线 -->
          <div class="grid-lines">
            <div v-for="i in boardDimension" :key="`h-${i}`" class="h-line" 
                :style="{ top: (i - 1) * cellSize + 'px' }"></div>
            <div v-for="i in boardDimension" :key="`v-${i}`" class="v-line" 
                :style="{ left: (i - 1) * cellSize + 'px' }"></div>
          </div>
          
          <!-- 星位点 -->
          <div v-for="point in starPoints" :key="`star-${point.x}-${point.y}`" 
              class="star-point"
              :style="{ left: point.x * cellSize + 'px', top: point.y * cellSize + 'px' }"></div>
          
          <!-- 棋子 -->
          <div v-for="(stone, index) in stones" :key="`stone-${index}`" 
              class="stone" 
              :class="stone.color"
              :style="{ left: stone.x * cellSize + 'px', top: stone.y * cellSize + 'px' }">
            <span v-if="stone.isLast" class="last-move-marker"></span>
          </div>
          
          <!-- 点击区域 -->
          <div v-for="i in boardDimension" :key="`row-${i}`" class="board-row">
            <div v-for="j in boardDimension" :key="`cell-${i}-${j}`" 
                class="board-cell"
                :style="{ 
                  width: cellSize + 'px', 
                  height: cellSize + 'px',
                  left: (j - 1) * cellSize - cellSize/2 + 'px', 
                  top: (i - 1) * cellSize - cellSize/2 + 'px' 
                }"
                @click="placeStone(j - 1, i - 1)"></div>
          </div>
          
          <!-- 游戏开始前的桌布 -->
          <div class="board-cover" v-if="!gameStarted" @click="startGame">
            <div class="cover-content">
              <div class="cover-logo">
                <div class="stone black"></div>
                <div class="stone white"></div>
              </div>
              <h2>AI 围棋</h2>
              <p>选择难度并点击开始游戏</p>
              <div class="cover-difficulty">
                <button 
                  v-for="level in difficultyLevels" 
                  :key="level.value"
                  @click.stop="setInitialDifficulty(level.value)"
                  class="difficulty-btn"
                  :class="{ active: currentDifficulty === level.value }"
                >
                  {{ level.label }}
                </button>
              </div>
              <button class="start-btn" @click.stop="startGame">开始游戏</button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧功能区 -->
      <div class="game-sidebar">
        <div class="game-header">
          <h1>AI 围棋</h1>
          <div class="game-info">
            <div class="player-info">
              <div class="player black">
                <div class="stone black"></div>
                <span>黑棋 (玩家)</span>
                <span class="score">{{ blackScore }}</span>
              </div>
              <div class="player white">
                <div class="stone white"></div>
                <span>白棋 (AI)</span>
                <span class="score">{{ whiteScore }}</span>
              </div>
            </div>
            <div class="game-status">{{ gameStatus }}</div>
          </div>
          
          <div class="difficulty-selector">
            <span>AI难度:</span>
            <div class="difficulty-options">
              <button 
                v-for="level in difficultyLevels" 
                :key="level.value"
                @click="setDifficulty(level.value)"
                class="difficulty-btn"
                :class="{ active: currentDifficulty === level.value }"
              >
                {{ level.label }}
              </button>
            </div>
          </div>
          
          <div class="game-controls">
            <button @click="startNewGame" class="control-btn">新游戏</button>
            <button @click="pass" class="control-btn">虚着</button>
            <button @click="undo" class="control-btn" :disabled="!canUndo">悔棋</button>
            <button @click="resign" class="control-btn danger">认输</button>
          </div>
          
          <div class="game-instructions">
            <h3>游戏说明</h3>
            <ul>
              <li>黑棋先行，点击棋盘落子</li>
              <li>围住对方棋子可以提子得分</li>
              <li>虚着：跳过当前回合</li>
              <li>悔棋：撤销上一步操作</li>
              <li>认输：结束当前对局</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    
    <div class="game-message" v-if="showMessage">
      <div class="message-content">
        <p>{{ messageText }}</p>
        <div class="message-buttons">
          <button v-if="messageNeedConfirm" @click="confirmMessage" class="control-btn">确定</button>
          <button v-if="messageNeedConfirm" @click="cancelMessage" class="control-btn secondary">取消</button>
          <button v-if="!messageNeedConfirm" @click="closeMessage" class="control-btn">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue';

// 棋盘尺寸和配置
const boardDimension = 19; // 19x19 标准棋盘
const boardRef = ref(null);
const boardSize = ref(700); // 初始棋盘大小
const cellSize = computed(() => boardSize.value / (boardDimension - 1));

// 难度级别 - 添加简单模式
const difficultyLevels = [
  { value: 'beginner', label: '简单' },
  { value: 'easy', label: '普通' },
  { value: 'medium', label: '高手' },
  { value: 'expert', label: '专家' }
];
const currentDifficulty = ref('easy'); // 默认普通难度

// 游戏状态 - 添加游戏是否已开始的状态
const gameStarted = ref(false);
const currentPlayer = ref('black'); // 黑棋先行
const stones = ref([]); // 棋盘上的所有棋子
const gameStatus = ref('请点击开始游戏');
const blackScore = ref(0);
const whiteScore = ref(0);
const gameHistory = ref([]); // 游戏历史记录
const canUndo = computed(() => gameHistory.value.length > 0 && gameStarted.value);
const showMessage = ref(false);
const messageText = ref('');
const gameActive = ref(false); // 游戏是否进行中

// 星位点位置 (9个星位点)
const starPoints = [
  { x: 3, y: 3 }, { x: 9, y: 3 }, { x: 15, y: 3 },
  { x: 3, y: 9 }, { x: 9, y: 9 }, { x: 15, y: 9 },
  { x: 3, y: 15 }, { x: 9, y: 15 }, { x: 15, y: 15 }
];

// 初始化棋盘
onMounted(() => {
  adjustBoardSize();
  window.addEventListener('resize', adjustBoardSize);
});

// 调整棋盘大小以适应屏幕 - 修改为优先考虑棋盘大小
const adjustBoardSize = () => {
  if (!boardRef.value) return;
  
  const containerWidth = boardRef.value.parentElement.clientWidth;
  const containerHeight = window.innerHeight * 0.85; // 使用更多的屏幕高度
  const maxSize = Math.min(containerWidth, containerHeight);
  boardSize.value = Math.max(400, Math.min(700, maxSize - 40)); // 增大最小和最大尺寸
};

// 落子 - 添加游戏开始检查
const placeStone = (x, y) => {
  if (!gameStarted.value) {
    startGame();
    return;
  }
  
  if (currentPlayer.value !== 'black') {
    showMessageBox('请等待AI落子');
    return;
  }
  
  // 检查位置是否已有棋子
  if (getStoneAt(x, y)) {
    showMessageBox('此位置已有棋子');
    return;
  }
  
  // 保存当前棋盘状态到历史记录
  saveGameState();
  
  // 清除上一手标记
  clearLastMoveMarker();
  
  // 放置玩家的棋子
  const newStone = { x, y, color: 'black', isLast: true };
  stones.value.push(newStone);
  
  // 检查提子
  const captured = checkCapture(x, y, 'white');
  if (captured.length > 0) {
    blackScore.value += captured.length;
    removeStones(captured);
  }
  
  // 检查是否结束游戏
  if (checkGameEnd()) {
    return;
  }
  
  // 切换到AI回合
  currentPlayer.value = 'white';
  gameStatus.value = 'AI思考中...';
  
  // AI落子 (延迟以模拟思考) - 根据难度调整思考时间
  const thinkingTime = getAIThinkingTime();
  setTimeout(() => {
    aiMove();
  }, thinkingTime);
};

// 根据难度获取AI思考时间
const getAIThinkingTime = () => {
  switch (currentDifficulty.value) {
    case 'beginner': return 300;  // 简单模式思考很快
    case 'easy': return 600;      // 普通模式稍微思考
    case 'medium': return 800;    // 高手模式需要思考
    case 'expert': return 1000;   // 专家模式思考最久
    default: return 600;
  }
};

// 设置难度
const setDifficulty = (difficulty) => {
  currentDifficulty.value = difficulty;
  // 如果游戏已经开始，询问是否重新开始
  if (stones.value.length > 0) {
    showMessageBox('更改难度将重新开始游戏，是否继续？', true, startNewGame);
  }
};

// AI落子
const aiMove = () => {
  // 保存当前棋盘状态到历史记录
  saveGameState();
  
  // 清除上一手标记
  clearLastMoveMarker();
  
  // 检查是否应该投降
  if (shouldResign()) {
    aiResign();
    return;
  }
  
  // 根据难度选择AI策略
  let move;
  switch (currentDifficulty.value) {
    case 'expert':
      move = getExpertMove();
      break;
    case 'medium':
      move = getMediumMove();
      break;
    case 'beginner':
      move = getBeginnerMove();
      break;
    default:
      move = getEasyMove();
  }
  
  if (!move) {
    // AI没有有效的落子位置，选择虚着
    currentPlayer.value = 'black';
    gameStatus.value = '轮到黑棋落子';
    showMessageBox('AI选择虚着');
    return;
  }
  
  // 放置AI的棋子
  const newStone = { x: move.x, y: move.y, color: 'white', isLast: true };
  stones.value.push(newStone);
  
  // 检查提子
  const captured = checkCapture(move.x, move.y, 'black');
  if (captured.length > 0) {
    whiteScore.value += captured.length;
    removeStones(captured);
  }
  
  // 检查是否结束游戏
  if (checkGameEnd()) {
    return;
  }
  
  // 切换回玩家回合
  currentPlayer.value = 'black';
  gameStatus.value = '轮到黑棋落子';
};

// 检查落子是否会导致自杀
const wouldBeSuicide = (x, y, color) => {
  // 如果位置已有棋子，不能落子
  if (getStoneAt(x, y)) return true;
  
  // 临时放置一个棋子
  const tempStone = { x, y, color };
  stones.value.push(tempStone);
  
  // 检查这个棋子是否有气
  const hasLiberty = hasLiberties(x, y, color);
  
  // 检查是否能提走对方的棋子
  const opponentColor = color === 'black' ? 'white' : 'black';
  const canCapture = checkCapture(x, y, opponentColor, true).length > 0;
  
  // 移除临时棋子
  stones.value.pop();
  
  // 如果没有气且不能提走对方的棋子，则是自杀
  return !hasLiberty && !canCapture;
};

// 寻找所有有效的落子位置
const findValidMoves = () => {
  const validMoves = [];
  
  // 遍历整个棋盘
  for (let x = 0; x < boardDimension; x++) {
    for (let y = 0; y < boardDimension; y++) {
      // 检查位置是否为空
      if (!getStoneAt(x, y)) {
        // 检查落子是否会导致自杀
        if (!wouldBeSuicide(x, y, 'white')) {
          validMoves.push({ x, y });
        }
      }
    }
  }
  
  return validMoves;
};

// 简单模式AI策略 - 完全随机，不考虑任何策略
const getBeginnerMove = () => {
  // 找到所有空位
  const emptyPositions = [];
  
  for (let x = 0; x < boardDimension; x++) {
    for (let y = 0; y < boardDimension; y++) {
      if (!getStoneAt(x, y)) {
        emptyPositions.push({ x, y });
      }
    }
  }
  
  if (emptyPositions.length === 0) return null;
  
  // 完全随机选择一个位置，不考虑是否会自杀
  const randomIndex = Math.floor(Math.random() * emptyPositions.length);
  const move = emptyPositions[randomIndex];
  
  // 如果这个位置会导致自杀，尝试找另一个位置
  if (wouldBeSuicide(move.x, move.y, 'white')) {
    // 在简单模式下，有50%的概率会选择一个不会自杀的位置
    if (Math.random() < 0.5) {
      const validMoves = findValidMoves();
      if (validMoves.length > 0) {
        const validIndex = Math.floor(Math.random() * validMoves.length);
        return validMoves[validIndex];
      }
    }
  }
  
  return move;
};

// 普通难度AI策略
const getEasyMove = () => {
  const validMoves = findValidMoves();
  if (validMoves.length === 0) return null;
  
  // 随机选择一个有效位置
  const randomIndex = Math.floor(Math.random() * validMoves.length);
  return validMoves[randomIndex];
};

// 高手难度AI策略
const getMediumMove = () => {
  const validMoves = findValidMoves();
  if (validMoves.length === 0) return null;
  
  // 尝试找到可以提子的位置
  const captureMoves = validMoves.filter(move => {
    return checkCapture(move.x, move.y, 'black', true).length > 0;
  });
  
  if (captureMoves.length > 0) {
    // 优先选择可以提子最多的位置
    captureMoves.sort((a, b) => {
      const capturesA = checkCapture(a.x, a.y, 'black', true).length;
      const capturesB = checkCapture(b.x, b.y, 'black', true).length;
      return capturesB - capturesA;
    });
    return captureMoves[0];
  }
  
  // 如果没有可以提子的位置，尝试找到靠近中心的位置
  const centerX = Math.floor(boardDimension / 2);
  const centerY = Math.floor(boardDimension / 2);
  
  validMoves.sort((a, b) => {
    const distA = Math.sqrt(Math.pow(a.x - centerX, 2) + Math.pow(a.y - centerY, 2));
    const distB = Math.sqrt(Math.pow(b.x - centerX, 2) + Math.pow(b.y - centerY, 2));
    return distA - distB;
  });
  
  // 选择前30%的位置中的随机一个
  const topMoves = validMoves.slice(0, Math.max(1, Math.floor(validMoves.length * 0.3)));
  const randomIndex = Math.floor(Math.random() * topMoves.length);
  return topMoves[randomIndex];
};

// 专家难度AI策略
const getExpertMove = () => {
  const validMoves = findValidMoves();
  if (validMoves.length === 0) return null;
  
  // 尝试找到可以提子的位置
  const captureMoves = validMoves.filter(move => {
    return checkCapture(move.x, move.y, 'black', true).length > 0;
  });
  
  if (captureMoves.length > 0) {
    // 优先选择可以提子最多的位置
    captureMoves.sort((a, b) => {
      const capturesA = checkCapture(a.x, a.y, 'black', true).length;
      const capturesB = checkCapture(b.x, b.y, 'black', true).length;
      return capturesB - capturesA;
    });
    return captureMoves[0];
  }
  
  // 评估每个位置的战略价值
  const scoredMoves = validMoves.map(move => {
    let score = 0;
    
    // 靠近中心加分
    const centerX = Math.floor(boardDimension / 2);
    const centerY = Math.floor(boardDimension / 2);
    const distanceToCenter = Math.sqrt(Math.pow(move.x - centerX, 2) + Math.pow(move.y - centerY, 2));
    score += (boardDimension / 2 - distanceToCenter) * 0.5;
    
    // 靠近自己的棋子加分
    const nearbyFriendly = countNearbyStones(move.x, move.y, 'white', 3);
    score += nearbyFriendly * 2;
    
    // 靠近对方的棋子也加分（但分值较低）
    const nearbyEnemy = countNearbyStones(move.x, move.y, 'black', 3);
    score += nearbyEnemy;
    
    // 靠近边缘减分
    const distanceToEdge = Math.min(
      move.x, 
      move.y, 
      boardDimension - 1 - move.x, 
      boardDimension - 1 - move.y
    );
    if (distanceToEdge < 2) {
      score -= (2 - distanceToEdge) * 3;
    }
    
    // 靠近星位点加分
    const nearestStarPoint = starPoints.reduce((nearest, point) => {
      const distance = Math.sqrt(Math.pow(move.x - point.x, 2) + Math.pow(move.y - point.y, 2));
      return distance < nearest ? distance : nearest;
    }, Infinity);
    
    if (nearestStarPoint < 3) {
      score += (3 - nearestStarPoint) * 2;
    }
    
    return { ...move, score };
  });
  
  // 按分数排序
  scoredMoves.sort((a, b) => b.score - a.score);
  
  // 从前20%的位置中随机选择一个（增加一些随机性）
  const topMoves = scoredMoves.slice(0, Math.max(1, Math.floor(scoredMoves.length * 0.2)));
  const randomIndex = Math.floor(Math.random() * topMoves.length);
  return topMoves[randomIndex];
};

// 计算指定范围内特定颜色棋子的数量
const countNearbyStones = (x, y, color, range) => {
  let count = 0;
  
  for (let i = Math.max(0, x - range); i <= Math.min(boardDimension - 1, x + range); i++) {
    for (let j = Math.max(0, y - range); j <= Math.min(boardDimension - 1, y + range); j++) {
      if (i === x && j === y) continue;
      
      const stone = getStoneAt(i, j);
      if (stone && stone.color === color) {
        // 根据距离计算权重
        const distance = Math.sqrt(Math.pow(i - x, 2) + Math.pow(j - y, 2));
        if (distance <= range) {
          count += 1 / distance; // 距离越近权重越大
        }
      }
    }
  }
  
  return count;
};

// 检查AI是否应该投降
const shouldResign = () => {
  // 简单模式下不投降
  if (currentDifficulty.value === 'beginner') return false;
  
  // 只有在中等或专家难度下，AI才会考虑投降
  if (currentDifficulty.value === 'easy') return false;
  
  // 如果游戏刚开始，不投降
  if (stones.value.length < 30) return false;
  
  // 计算黑白棋子数量差距
  const blackStones = stones.value.filter(stone => stone.color === 'black').length;
  const whiteStones = stones.value.filter(stone => stone.color === 'white').length;
  
  // 计算分数差距
  const scoreDifference = blackScore.value - whiteScore.value;
  
  // 根据难度设置不同的投降阈值
  const threshold = currentDifficulty.value === 'expert' ? 15 : 20;
  
  // 如果黑棋领先太多，AI考虑投降
  if (scoreDifference > threshold || (blackStones - whiteStones > threshold)) {
    // 专家级别有20%的概率坚持下去
    if (currentDifficulty.value === 'expert' && Math.random() < 0.2) {
      return false;
    }
    return true;
  }
  
  return false;
};

// AI投降
const aiResign = () => {
  gameStatus.value = '白棋(AI)认输，黑棋获胜！';
  gameActive.value = false;
  showMessageBox('AI认为局势已定，选择认输。黑棋获胜！');
};

// 玩家认输
const resign = () => {
  if (!gameActive.value) return;
  
  showMessageBox('确定要认输吗？', true, () => {
    gameStatus.value = '黑棋(玩家)认输，白棋获胜！';
    gameActive.value = false;
    showMessageBox('您已认输，白棋获胜！');
  });
};

// 检查提子
const checkCapture = (x, y, opponentColor, simulate = false) => {
  const capturedStones = [];
  
  // 检查四个方向
  const directions = [
    { dx: -1, dy: 0 }, // 左
    { dx: 1, dy: 0 },  // 右
    { dx: 0, dy: -1 }, // 上
    { dx: 0, dy: 1 }   // 下
  ];
  
  for (const dir of directions) {
    const nx = x + dir.dx;
    const ny = y + dir.dy;
    
    // 检查边界
    if (nx < 0 || nx >= boardDimension || ny < 0 || ny >= boardDimension) continue;
    
    const stone = getStoneAt(nx, ny);
    if (stone && stone.color === opponentColor) {
      // 检查这个棋子所在的组是否没有气
      if (!hasLiberties(nx, ny, opponentColor)) {
        // 找出所有需要提走的棋子
        const group = findConnectedStones(nx, ny, opponentColor);
        capturedStones.push(...group);
      }
    }
  }
  
  return capturedStones;
};

// 找出与指定棋子相连的所有同色棋子
const findConnectedStones = (x, y, color) => {
  const visited = new Set();
  const group = [];
  
  const findGroup = (x, y) => {
    const key = `${x},${y}`;
    if (visited.has(key)) return;
    
    visited.add(key);
    const stone = getStoneAt(x, y);
    if (!stone || stone.color !== color) return;
    
    group.push(stone);
    
    // 检查四个方向
    if (x > 0) findGroup(x - 1, y);
    if (x < boardDimension - 1) findGroup(x + 1, y);
    if (y > 0) findGroup(x, y - 1);
    if (y < boardDimension - 1) findGroup(x, y + 1);
  };
  
  findGroup(x, y);
  return group;
};

// 移除棋子
const removeStones = (stonesToRemove) => {
  for (const stone of stonesToRemove) {
    const index = stones.value.findIndex(s => s.x === stone.x && s.y === stone.y);
    if (index !== -1) {
      stones.value.splice(index, 1);
    }
  }
};

// 获取指定位置的棋子
const getStoneAt = (x, y) => {
  return stones.value.find(stone => stone.x === x && stone.y === y);
};

// 检查棋子是否有气
const hasLiberties = (x, y, color, stonesList = stones.value) => {
  const visited = new Set();
  const group = [];
  
  // 找出与当前棋子相连的所有同色棋子
  const findGroup = (x, y) => {
    const key = `${x},${y}`;
    if (visited.has(key)) return;
    
    visited.add(key);
    const stone = getStoneAtFromList(x, y, stonesList);
    if (!stone || stone.color !== color) return;
    
    group.push({ x, y });
    
    // 检查四个方向
    if (x > 0) findGroup(x - 1, y);
    if (x < boardDimension - 1) findGroup(x + 1, y);
    if (y > 0) findGroup(x, y - 1);
    if (y < boardDimension - 1) findGroup(x, y + 1);
  };
  
  findGroup(x, y);
  
  // 检查组中的每个棋子是否有气
  for (const stone of group) {
    // 检查四个方向是否有空位
    if (stone.x > 0 && !getStoneAtFromList(stone.x - 1, stone.y, stonesList)) return true;
    if (stone.x < boardDimension - 1 && !getStoneAtFromList(stone.x + 1, stone.y, stonesList)) return true;
    if (stone.y > 0 && !getStoneAtFromList(stone.x, stone.y - 1, stonesList)) return true;
    if (stone.y < boardDimension - 1 && !getStoneAtFromList(stone.x, stone.y + 1, stonesList)) return true;
  }
  
  return false;
};

// 从指定列表中获取棋子
const getStoneAtFromList = (x, y, stonesList) => {
  return stonesList.find(stone => stone.x === x && stone.y === y);
};

// 清除上一手标记
const clearLastMoveMarker = () => {
  stones.value.forEach(stone => {
    stone.isLast = false;
  });
};

// 虚着
const pass = () => {
  if (currentPlayer.value !== 'black') {
    showMessageBox('请等待AI落子');
    return;
  }
  
  // 保存当前棋盘状态到历史记录
  saveGameState();
  
  // 清除上一手标记
  clearLastMoveMarker();
  
  // 玩家选择虚着
  currentPlayer.value = 'white';
  gameStatus.value = 'AI思考中...';
  
  // AI回合
  setTimeout(() => {
    aiMove();
  }, 1000);
};

// 悔棋
const undo = () => {
  if (gameHistory.value.length === 0) return;
  
  // 恢复到上一个状态
  const lastState = gameHistory.value.pop();
  stones.value = JSON.parse(JSON.stringify(lastState.stones));
  currentPlayer.value = lastState.currentPlayer;
  blackScore.value = lastState.blackScore;
  whiteScore.value = lastState.whiteScore;
  gameStatus.value = currentPlayer.value === 'black' ? '轮到黑棋落子' : 'AI思考中...';
  
  // 如果悔棋后是AI回合，再悔一次
  if (currentPlayer.value === 'white' && gameHistory.value.length > 0) {
    undo();
  }
};

// 保存游戏状态
const saveGameState = () => {
  gameHistory.value.push({
    stones: JSON.parse(JSON.stringify(stones.value)),
    currentPlayer: currentPlayer.value,
    blackScore: blackScore.value,
    whiteScore: whiteScore.value
  });
};

// 开始新游戏
const startNewGame = () => {
  stones.value = [];
  currentPlayer.value = 'black';
  gameStatus.value = '轮到黑棋落子';
  blackScore.value = 0;
  whiteScore.value = 0;
  gameHistory.value = [];
  gameActive.value = true;
};

// 检查游戏是否结束
const checkGameEnd = () => {
  // 简单实现：如果棋盘上的棋子数量超过一定阈值，游戏结束
  if (stones.value.length >= boardDimension * boardDimension * 0.8) {
    const winner = blackScore.value > whiteScore.value ? '黑棋' : 
                  blackScore.value < whiteScore.value ? '白棋' : '平局';
    gameStatus.value = `游戏结束，${winner}胜利！`;
    showMessageBox(`游戏结束，${winner}胜利！`);
    return true;
  }
  return false;
};

// 显示消息框
const showMessageBox = (message, needConfirm = false, confirmCallback = null) => {
  messageText.value = message;
  showMessage.value = true;
  
  if (needConfirm) {
    messageConfirmCallback.value = confirmCallback;
    messageNeedConfirm.value = true;
  } else {
    messageNeedConfirm.value = false;
    messageConfirmCallback.value = null;
  }
};

// 添加确认回调和确认标志
const messageConfirmCallback = ref(null);
const messageNeedConfirm = ref(false);

// 确认消息
const confirmMessage = () => {
  showMessage.value = false;
  if (messageConfirmCallback.value) {
    messageConfirmCallback.value();
  }
};

// 取消消息
const cancelMessage = () => {
  showMessage.value = false;
};

// 添加关闭消息的方法
const closeMessage = () => {
  showMessage.value = false;
};

// 设置初始难度（不重新开始游戏）
const setInitialDifficulty = (difficulty) => {
  currentDifficulty.value = difficulty;
};

// 开始游戏
const startGame = () => {
  if (gameStarted.value) return;
  
  gameStarted.value = true;
  gameActive.value = true;
  gameStatus.value = '轮到黑棋落子';
  startNewGame();
};
</script>

<style scoped>
.go-game-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  max-width: 1200px; /* 增加最大宽度 */
  margin: 0 auto;
  height: calc(100vh - 40px); /* 使用更多的视口高度 */
}

/* 新增水平布局 */
.game-layout {
  display: flex;
  width: 100%;
  gap: 20px;
  height: 100%;
}

/* 调整棋盘容器 */
.board-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 0; /* 防止溢出 */
}

/* 新增侧边栏样式 */
.game-sidebar {
  width: 300px;
  padding: 20px;
  background-color: #f8fafc;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.game-header {
  width: 100%;
  text-align: left;
}

.game-header h1 {
  margin-bottom: 16px;
  color: #1e293b;
  font-size: 24px;
}

.game-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 16px;
}

.player-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.player {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stone {
  width: 28px;  /* 增大棋子尺寸 */
  height: 28px; /* 增大棋子尺寸 */
  border-radius: 50%;
  position: absolute;
  transform: translate(-50%, -50%);
  z-index: 10;
  transition: all 0.2s ease; /* 添加过渡效果 */
}

.player .stone {
  position: relative;
  transform: none;
  width: 20px; /* 保持玩家信息区域的棋子大小不变 */
  height: 20px;
}

.stone.black {
  background: radial-gradient(circle at 35% 35%, #444, #000); /* 渐变背景 */
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.5), inset 0 2px 8px rgba(255, 255, 255, 0.2); /* 增强阴影 */
}

.stone.white {
  background: radial-gradient(circle at 35% 35%, #fff, #e0e0e0); /* 渐变背景 */
  border: 1px solid #ccc;
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.2), inset 0 -2px 8px rgba(0, 0, 0, 0.05); /* 增强阴影 */
}

.score {
  font-weight: bold;
  margin-left: 4px;
}

.game-status {
  font-size: 16px;
  font-weight: 500;
  color: #475569;
  padding: 10px;
  background-color: #e2e8f0;
  border-radius: 4px;
  margin-top: 10px;
}

.difficulty-selector {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin: 16px 0;
}

.difficulty-options {
  display: flex;
  gap: 8px;
  margin-top: 6px;
  flex-wrap: wrap;
}

.difficulty-btn {
  padding: 6px 12px;
  background-color: #e2e8f0;
  color: #475569;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.difficulty-btn:hover {
  background-color: #cbd5e1;
}

.difficulty-btn.active {
  background-color: #3b82f6;
  color: white;
}

.game-controls {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin: 16px 0;
}

.control-btn {
  padding: 10px 16px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.control-btn:hover {
  background-color: #2563eb;
}

.control-btn:disabled {
  background-color: #94a3b8;
  cursor: not-allowed;
}

.control-btn.danger {
  background-color: #ef4444;
}

.control-btn.danger:hover {
  background-color: #dc2626;
}

.control-btn.secondary {
  background-color: #64748b;
}

.control-btn.secondary:hover {
  background-color: #475569;
}

.go-board {
  position: relative;
  background-color: #deb887; /* 棋盘颜色 */
  border: 2px solid #8b4513;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 新增游戏说明样式 */
.game-instructions {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e2e8f0;
}

.game-instructions h3 {
  font-size: 16px;
  margin-bottom: 10px;
  color: #1e293b;
}

.game-instructions ul {
  padding-left: 20px;
  font-size: 14px;
  color: #64748b;
}

.game-instructions li {
  margin-bottom: 6px;
}

/* 其余样式保持不变 */
.grid-lines {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.h-line, .v-line {
  position: absolute;
  background-color: #000;
}

.h-line {
  height: 1px;
  width: 100%;
}

.v-line {
  width: 1px;
  height: 100%;
}

.star-point {
  position: absolute;
  width: 6px;
  height: 6px;
  background-color: #000;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}

.board-row {
  position: relative;
}

.board-cell {
  position: absolute;
  cursor: pointer;
  z-index: 5;
}

.last-move-marker {
  position: absolute;
  width: 8px;
  height: 8px;
  background-color: red;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.game-message {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.message-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  max-width: 300px;
}

.message-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 16px;
}

/* 响应式设计 - 调整为垂直布局 */
@media (max-width: 900px) {
  .game-layout {
    flex-direction: column;
  }
  
  .game-sidebar {
    width: 100%;
    order: 2;
  }
  
  .board-container {
    order: 1;
    margin-bottom: 20px;
  }
  
  .game-controls {
    flex-direction: row;
    flex-wrap: wrap;
  }
}

/* 更小屏幕的调整 */
@media (max-width: 600px) {
  .go-game-container {
    padding: 10px;
    height: auto;
  }
  
  .game-header h1 {
    font-size: 20px;
  }
  
  .control-btn {
    padding: 8px 12px;
    font-size: 12px;
  }
}

/* 暗色主题 */
@media (prefers-color-scheme: dark) {
  .game-sidebar {
    background-color: #1e293b;
  }
  
  .game-header h1 {
    color: #e2e8f0;
  }
  
  .game-status {
    color: #cbd5e1;
    background-color: #334155;
  }
  
  .go-board {
    background-color: #b89268;
    border-color: #6b4226;
  }
  
  .message-content {
    background-color: #334155;
    color: #e2e8f0;
  }
  
  .difficulty-btn {
    background-color: #334155;
    color: #cbd5e1;
  }
  
  .difficulty-btn:hover {
    background-color: #475569;
  }
  
  .difficulty-btn.active {
    background-color: #3b82f6;
    color: white;
  }
  
  .game-instructions {
    border-top-color: #334155;
  }
  
  .game-instructions h3 {
    color: #e2e8f0;
  }
  
  .game-instructions ul {
    color: #94a3b8;
  }
}

/* 添加棋子放置动画 */
@keyframes placeStone {
  0% { transform: translate(-50%, -50%) scale(1.3); opacity: 0.7; }
  100% { transform: translate(-50%, -50%) scale(1); opacity: 1; }
}

.stone:last-child {
  animation: placeStone 0.3s ease-out;
}

/* 棋盘桌布样式 */
.board-cover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #8a5a44, #deb887);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 50;
  cursor: pointer;
  border-radius: 4px;
  box-shadow: inset 0 0 20px rgba(0, 0, 0, 0.3);
  overflow: hidden;
}

.board-cover::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect width="50" height="50" fill="rgba(0,0,0,0.05)"/><rect x="50" y="50" width="50" height="50" fill="rgba(0,0,0,0.05)"/></svg>');
  background-size: 30px 30px;
  opacity: 0.3;
}

.cover-content {
  background-color: rgba(255, 255, 255, 0.9);
  padding: 30px;
  border-radius: 10px;
  text-align: center;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  max-width: 80%;
  z-index: 51;
}

.cover-logo {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-bottom: 15px;
}

.cover-logo .stone {
  position: relative;
  width: 30px;
  height: 30px;
  transform: none;
  display: inline-block;
}

.cover-content h2 {
  font-size: 24px;
  margin-bottom: 10px;
  color: #1e293b;
}

.cover-content p {
  margin-bottom: 20px;
  color: #64748b;
}

.cover-difficulty {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.start-btn {
  padding: 12px 24px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.2s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.start-btn:hover {
  background-color: #2563eb;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

/* 暗色主题下的桌布样式 */
@media (prefers-color-scheme: dark) {
  .board-cover {
    background: linear-gradient(135deg, #4a3528, #8a6642);
  }
  
  .cover-content {
    background-color: rgba(30, 41, 59, 0.9);
  }
  
  .cover-content h2 {
    color: #e2e8f0;
  }
  
  .cover-content p {
    color: #94a3b8;
  }
}
</style> 